package com.niit.search.mapper;

import com.niit.search.entity.SearchHistory;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;

@Mapper
public interface SearchHistoryMapper {
    @Insert("INSERT INTO tb_search (user_id, keyword, is_deleted, search_num) VALUES (#{userId}, #{keyword}, 0, 1)")
    void insertHistory(@Param("userId") Long userId, @Param("keyword") String keyword);

    @Select("SELECT * FROM tb_search WHERE user_id = #{userId} AND is_deleted = 0 AND search_time >= DATE_SUB(NOW(), INTERVAL 24 HOUR) ORDER BY search_time DESC LIMIT 5")
    List<SearchHistory> getHistoryByUserId(@Param("userId") Long userId);
    
    @Update("UPDATE tb_search SET is_deleted = 1 WHERE id = #{id} AND user_id = #{userId}")
    int deleteHistoryById(@Param("id") Long id, @Param("userId") Long userId);
    
    @Update("UPDATE tb_search SET is_deleted = 1 WHERE keyword = #{keyword} AND user_id = #{userId}")
    int deleteHistoryByKeyword(@Param("keyword") String keyword, @Param("userId") Long userId);
    
    @Select("SELECT * FROM tb_search WHERE keyword = #{keyword} AND is_deleted = 0 LIMIT 1")
    SearchHistory findByKeyword(@Param("keyword") String keyword);
    
    @Update("UPDATE tb_search SET search_num = search_num + 1, search_time = NOW() WHERE keyword = #{keyword} AND is_deleted = 0")
    int incrementSearchCount(@Param("keyword") String keyword);
    
    @Select("SELECT t.* FROM tb_topic t JOIN tb_search s ON t.content = s.keyword WHERE s.is_deleted = 0 ORDER BY s.search_num DESC LIMIT 10")
    List<com.niit.search.entity.Topic> getHotTopics();
}